package edu.nwmissouri.galaxygames;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class EventCalendarFragment extends Fragment {
	
	//array list to store events
	public static ArrayList<Event> eventList = new ArrayList();
	
	//text view for display events
	TextView eventDisplay;
	LinearLayout eventLinearLayout;
	
	//stores whether or not the file has already been downloaded
	public static boolean eventsCached = false;
	
	
	
	
	@Override
	public void onCreate(Bundle bundle)
	{
	    super.onCreate(bundle);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup view, Bundle bundle)
	{
	    return inflater.inflate(R.layout.activity_event_calendar, view, false);
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		
	}
	
	@Override
	public void onStart(){
		
		super.onStart();
		
		
		//set eventDisplay to appropriate TextView in activity
				int inty = R.id.eventLinearDisplay;
				int inty2 = R.id.refreshButton;
				eventLinearLayout = (LinearLayout) getActivity().findViewById(R.id.eventLinearDisplay);
				
				//find and set up the on click listener for the refresh button
				Button refreshButton = (Button)getActivity().findViewById(R.id.refreshButton);
				
				refreshButton.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						
						
						//call method to refresh event list
						refreshEventList();
					}
				});
				
				if(!eventsCached){
				
					//attempt to download the file from the internet
					if(isNetworkAvailable()){
						
						//Create network dialog
						((MainActivity)getActivity()).makeEventLoadDialog();
						
						//reads the events calendar file from the internet
						readEventCalendar();
					}
					else{
						//if a connection is not available, notify the user and return to the main menu
						((MainActivity)getActivity()).makeNetworkErrorDialog();
					}
					
				}
				else if(eventsCached){
					populateEventList();
				}
		
	}
	
	//refresh the event list
	public void refreshEventList(){
		
		if(isNetworkAvailable()){
			
			//clear the event array list
			eventList = new ArrayList();
			
			//clear the event list
			eventLinearLayout.removeAllViews();
			
			//Create network dialog
			((MainActivity)getActivity()).makeEventLoadDialog();
			
			//reads the events calendar file from the internet
			readEventCalendar();
		}
		else{
			//if a connection is not available, notify the user and return to the main menu
			((MainActivity)getActivity()).makeNetworkErrorDialog();
		}
	}
	
	//returns true if the device has a connection to the internet
	public boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) 
			      getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
			    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
			    // if no network is available networkInfo will be null
			    // otherwise check if we are connected
			    if (networkInfo != null && networkInfo.isConnected()) {
			        return true;
			    }
			    return false;
   }
	
	//reads the event calendar from the server
	public void readEventCalendar(){
		DownloadWebPageTask task = new DownloadWebPageTask(((MainActivity)getActivity()));
	    task.execute(new String[] { "http://dl.dropbox.com/u/59131634/Tester.txt" });
	}
	
	//recieves lines of text, places the text appropriately into an events and adds the events
	//to the event list.  Once completed, it caches the events and tells the list to be populated.
	public void createEvents(String line){
		
		//split the string into an array by lines
		String [] lineArray = line.split(";");
		
		//create an event for each line, and add it to the list
		for(int i = 0; i<lineArray.length; i++){
			//split line into parts
			String[] currentLineParts = lineArray[i].split("#");
			
			//create an event
			Event eventToAdd = new Event(currentLineParts[0], currentLineParts[1], currentLineParts[2],
					currentLineParts[3], currentLineParts[4]);
			
			//add to list
			eventList.add(eventToAdd);
		}
		
		//the events are not cached
		eventsCached = true;
		
		//populate the list
		populateEventList();
		
	}
	
	//populates the text view with all currently loaded events
			public void populateEventList(){
				
				//create a string to display basic event information
				String eventBasicInformation = "";
				
				//text view to add to scroll view
				TextView textViewToAdd;
				
				//border to separate event text views
				View border;
				
				for(int i = 0; i<eventList.size(); i++){
					
					//set text view params and id
					textViewToAdd = new TextView(getActivity().getBaseContext());
					textViewToAdd.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
					
					textViewToAdd.setId(i);
					textViewToAdd.setOnClickListener(new View.OnClickListener() {
							
							@Override
							public void onClick(View textViewClicked) {
								//retrieve the current event to show from the event list
								Event eventToShow = eventList.get(textViewClicked.getId());
								((MainActivity)getActivity()).makeMoreInfoDialog(eventToShow);
								
								
							}
						});
					
					Event currentEvent = eventList.get(i);
					
					//set text to current event's basic information
					textViewToAdd.setText("\n" + currentEvent.getBasicInfo() + "\n");
					textViewToAdd.setTextColor(Color.BLACK);
					textViewToAdd.setGravity(Gravity.CENTER_HORIZONTAL);
					
					//add textView to linear layout inside scroll view
					eventLinearLayout.addView(textViewToAdd);
					
					border = new View(getActivity().getBaseContext());
					border.setLayoutParams(new LinearLayout.LayoutParams(800, 1));
					border.setBackgroundColor(android.graphics.Color.BLACK);
					eventLinearLayout.addView(border);
					
				}
				
				
				
			}
	
	public void showResponse(String s){
		Toast.makeText(getActivity().getBaseContext(), s, Toast.LENGTH_LONG).show();
	}
	
	//caches the event list so it can be referenced later
	public void cacheEvents(String[] events) throws IOException{
		
	}
	
	private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
	    
	    private WeakReference<MainActivity> parent;
	    
	    public DownloadWebPageTask (MainActivity parentActivity)
	    {
		this.parent = new WeakReference<MainActivity>(parentActivity);
	    }
		 
	    @Override
	    protected String doInBackground(String... urls) {
	      String response = "";
	      for (String url : urls) {
	        DefaultHttpClient client = new DefaultHttpClient();
	        HttpGet httpGet = new HttpGet(url);
	        try {
	          HttpResponse execute = client.execute(httpGet);
	          InputStream content = execute.getEntity().getContent();

	          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
	          String s = "";
	          while ((s = buffer.readLine()) != null) {
	            response += s;
	          }

	        } catch (Exception e) {
	        	
	        }
	      }
	      return response;
	    }

	    @Override
	    protected void onPostExecute(String result) {
	    
	    	//close the alert dialog
	    	MainActivity parentActivity = parent.get();
	    	parentActivity.dismissNetworkDialog();
	    	createEvents(result);
	    }
	  }

}
